package ejemplosAR;

import processing.video.*;
import jp.nyatla.nyar4psg.*;
import processing.core.*;
import processing.opengl.*;
import javax.media.opengl.*; 

public class WithOpenGL extends PApplet {

	private static final long serialVersionUID = 1L;
	private static final String PARA = "/Users/marthagarzon/Desktop/Juan Manuel/Workspace/ModuloSimulacion/data/camera_para.dat";
	private static final String HIRO = "/Users/marthagarzon/Desktop/Juan Manuel/Workspace/ModuloSimulacion/data/patt.hiro";

	private Capture cam;
	private MultiMarker nya;
	private float[] gl_projection=new float[16];

	public void setup() {
		size(640,480,OPENGL);
		colorMode(RGB, 100);
		println(MultiMarker.VERSION);  
		cam=new Capture(this,640,480);
		nya=new MultiMarker(this,width,height,PARA,NyAR4PsgConfig.CONFIG_PSG);
		nya.addARMarker(HIRO,80);//id=0

		PMatrix3D m=nya.getProjectionMatrix().get();
		m.transpose();
		m.get(gl_projection);
	}


	@SuppressWarnings("static-access")
	public void draw()
	{
		float[] mv=new float[16];

		if (cam.available()) {
			cam.read();
			nya.detect(cam);
			background(0);
			nya.drawBackground(cam);

			PGraphicsOpenGL pgl = (PGraphicsOpenGL) g;
			GL gl = pgl.beginGL();

			int current_mode=getCurrentMatrixMode(gl);

			for(int i=0;i<1;i++){
				if(nya.isExistMarker(i)){

					gl.glMatrixMode(gl.GL_PROJECTION);
					gl.glLoadMatrixf(gl_projection, 0 );

					PMatrix3D m=nya.getMarkerMatrix(i);
					m.transpose();
					m.get(mv);
					gl.glMatrixMode( gl.GL_MODELVIEW );
					gl.glLoadIdentity();

					gl.glScaled( 1.0, -1.0, 1.0 );
					gl.glMultMatrixf(mv,0);

					drawGLObject(gl);
				}
			}
			gl.glMatrixMode(current_mode);
			pgl.endGL();
		}
	}

	public int getCurrentMatrixMode(GL i_gl)
	{
		int[] tmp=new int[1];
		i_gl.glGetIntegerv(GL.GL_MATRIX_MODE,tmp,0);
		return tmp[0];
	}

	public void drawGLObject(GL i_gl)
	{
		i_gl.glBegin(GL.GL_LINES);
		i_gl.glColor4f(1, 0, 0, 1);
		i_gl.glVertex3f(0,0,0);
		i_gl.glVertex3f(100,0,0);
		i_gl.glColor4f(0, 1, 0, 1);
		i_gl.glVertex3f(0,0,0);
		i_gl.glVertex3f(0,100,0);
		i_gl.glColor4f(0, 0, 1, 1);
		i_gl.glVertex3f(0,0,0);
		i_gl.glVertex3f(0,0,100);
		i_gl.glEnd();
	}


}
